/***
 * Copyright (c) 2021-2031 murenchao
 * fig is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *       http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package cool.taomu.software.fig.mqtt.client.paho;

import java.util.concurrent.TimeUnit;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CallbackTemplate implements MqttCallback {
	final static Logger LOG = LoggerFactory.getLogger(CallbackTemplate.class);
	private MqttClient client;
	private MqttConnectOptions options;

	public void setClient(MqttClient client) {
		this.client = client;
	}

	public void setOptions(MqttConnectOptions options) {
		this.options = options;
	}

	@Override
	public void connectionLost(Throwable cause) {
		LOG.debug("Client connectionLost: {}", cause.getMessage());
		try {
			client.reconnect();
			while (true) {
				try {
					TimeUnit.SECONDS.sleep(1);
					client.connect(this.options);
					if (client.isConnected()) {
						break;
					}
				} catch (MqttException | InterruptedException e) {
					LOG.info("clientId : {} 尝试重新连接",client.getClientId(),e);
					Thread.currentThread().interrupt();
				}
			}
		} catch (MqttException e1) {
			LOG.info("MqttExecption : ",e1);
		}
	}

	@Override
	public void deliveryComplete(IMqttDeliveryToken token) {
		for (String i : token.getTopics()) {
			LOG.debug("Client deliveryComplete : {}", i);
		}
	}

	@Override
	public void messageArrived(String topic, MqttMessage message) throws Exception {
	}

}
